//
//  SNFoodEditViewController.m
//  project
//
//  Created by 黄建华 on 2018/11/14.
//  Copyright © 2018年 黄建华. All rights reserved.
//

#import "SNFoodEditViewController.h"
#import "SNFoodMealEditTableViewCell.h"

@interface SNFoodEditViewController ()<JJSearchOptionViewDelegate, JJOptionViewDelegate>

@property (nonatomic, strong) SNShadowView   *infoView;
@property (nonatomic, strong) NSMutableArray *snFoodArray;
@property (nonatomic) BOOL isSelectFood;

@end

@implementation SNFoodEditViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.isSelectFood = NO;
    
    self.leftButton.hidden = NO;
    [self.leftButton setImageNormal:@"进入"];
    self.sbTitleLable.text = SN_Text(@"这餐吃了什么");
    
//    SNShadowView *shadowLine = [[SNShadowView alloc] init];
//    shadowLine.frame = SNFRAME(0, 20+FitSimpleIpx(0, 20) + 44, HHHWIDTH, 0);
//    [shadowLine showWithType:1];
//    [self.view addSubview:shadowLine];
    UIImageView *shadowLine = [[UIImageView alloc] init];
    shadowLine.frame = SNFRAME(0, 20+FitSimpleIpx(0, 20) + 44 -2, HHHWIDTH, 2);
    shadowLine.image = [UIImage image:@"lineImage"];
    [self.view addSubview:shadowLine];
    
    CGFloat height = 0;//目前是固定2样食物
    if (_dataArray.count > 2) {
        height = 70 *_dataArray.count;
    } else {
        height = 70*2;
    }
    
    _infoView                    = [[SNShadowView alloc] init];
    _infoView.frame              = SNFRAME(10, shadowLine.bottom +20, HHHWIDTH-20, 20+20+30 +height);
    _infoView.layer.borderWidth  = 0.5;
    _infoView.layer.borderColor  = SNCOLORGRAYLINE.CGColor;
    _infoView.layer.cornerRadius = 5.0;
    [self.view addSubview:_infoView];
    
    UILabel *nameLabel = [UILabel simpleWithRect:SNFRAME(30, 20, _infoView.width/2 -30, 20) withAlignment:NSTextAlignmentCenter withFontSize:SNFITFONTSIZE(14) withText:SN_Text(@"食物名称") withTextColor:[UIColor blackColor]];
    nameLabel.font = SNFONT(SNFITFONTSIZE(14));
    [_infoView addSubview:nameLabel];
    
    for (int i = 0; i < 3; i++) {
        UILabel *info = [UILabel simpleWithRect:SNFRAME(_infoView.width/2.0 +i*_infoView.width /6, 20, _infoView.width/2/3, 20) withAlignment:NSTextAlignmentCenter withFontSize:15.0 withText:@"" withTextColor:[UIColor blackColor]];
        info.font = SNFONT(SNFITFONTSIZE(14));
        info.adjustsFontSizeToFitWidth = YES;
        [_infoView addSubview:info];
        if (i == 0) {
            info.text = SN_Text(@"份量");
        }
        if (i == 1) {
            info.text = SN_Text(@"单位");
        }
        if (i == 2) {
            info.text = SN_Text(@"大卡");
        }
    }
    
    _tableView                = [[UITableView alloc] initWithFrame:SNFRAME(0, nameLabel.bottom +30, _infoView.width, height) style:UITableViewStylePlain];
    _tableView.dataSource     = self;
    _tableView.delegate       = self;
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    _tableView.scrollEnabled  = NO;
    [_infoView addSubview:_tableView];
    
    UIButton *saveButton = [[UIButton alloc] initWithFrame:SNFRAME(20, HHHHEIGHT - 55-FitSimpleIpx(0,20), HHHWIDTH - 40, 40)];
    saveButton.backgroundColor = [UIColor blackColor];
    [saveButton setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [saveButton setTitleColor:[UIColor grayColor] forState:UIControlStateHighlighted];
    [saveButton addCornerRadius:5.0 color:[UIColor blackColor] lineWidth:1];
    [saveButton setTitle:SN_Text(@"保存") forState:UIControlStateNormal];
    [saveButton addTarget:self action:@selector(endAndSave) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:saveButton];
}

- (void)setModel:(FoodEatModel *)model {
    _model = model;
     _snFoodArray = [NSMutableArray array];
    if (self.add) {
        NSDictionary *dic = @{@"name":@"", @"unit":@"", @"calory":@"", @"amount":@""};
        for (int i = 0; i < 2; i++) {
            [_snFoodArray addObject:dic];
        }
    } else {
        NSDictionary *dic = @{@"name":@"", @"unit":@"", @"calory":@"", @"amount":@""};
        for (int i = 0; i < 2; i++) {
            [_snFoodArray addObject:dic];
        }
        for (int k = 0; k <_model.foodListArray.count; k++) {
            NSDictionary *dic = [_model.foodListArray objectAtIndex:k];
            [_snFoodArray replaceObjectAtIndex:k withObject:dic];
        }
    }
    _dataArray = [NSMutableArray arrayWithArray:_snFoodArray];
    
    [_tableView reloadData];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return 70.0;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return _dataArray.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    static NSString             *identifier = @"SNFoodMealEditTableViewCell";
    SNFoodMealEditTableViewCell *cell       = [tableView cellForRowAtIndexPath:indexPath];
    
    if (nil == cell) {
        cell = [[SNFoodMealEditTableViewCell alloc] initWithStyle:(UITableViewCellStyleDefault) reuseIdentifier:identifier];
    }
    //更新数据
    cell.tag = indexPath.row;
    NSDictionary *dic = _dataArray[indexPath.row];
    [cell updateCellWithModel:dic];
    
    //    //背景颜色
    //    UIView *tempView1 = [[UIView alloc] initWithFrame:cell.frame];
    //    tempView1.backgroundColor   = [UIColor clearColor];
    //    cell.selectedBackgroundView = tempView1;
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    
    //食物选择
    cell.jjSearchView.delegate     = self;
    cell.unitJJSearchView.delegate = self;
    
    //重量编辑
    [cell.weightTx addTarget:self action:@selector(weightTxChange:) forControlEvents:UIControlEventEditingChanged];
    cell.weightTx.delegate = self;
    
    //卡路里编辑
    [cell.calorTx addTarget:self action:@selector(calorTxChange:) forControlEvents:UIControlEventEditingChanged];
    cell.calorTx.delegate = self;
    
    return cell;
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    SN_FoodClass.foodArray = [NSMutableArray array];
    if (!_add) {
     NSArray *array = [NSArray arrayWithArray:_model.foodListArray];
        for (NSDictionary *dic in array) {
            //    int food_alias_id = [dic[@"food_alias_id"]intValue];
            //    int food_id = [dic[@"food_id"]intValue];
            
            // 获取单位
            NSString *unit = dic[@"unit"];
            //获取单位对应的系数
            CGFloat unitValue = [SN_FoodClass getMultipleWithUnit:unit];
            
            // 获取重量
            NSInteger anount = [dic[@"amount"]integerValue];
            
            NSInteger calory =[dic[@"calory"]integerValue];
            //转换成100克对应的卡路里
            CGFloat weight = 1.0*unitValue *anount ;
            CGFloat everyUnitForG = 1.0*calory /weight;
            CGFloat cc = roundf(everyUnitForG*100);
            NSInteger caloryT = (int)cc;
            NSDictionary *dicT = @{@"name":dic[@"name"],@"state":@"1",@"food_id":@"1",@"calory":StrByInt(caloryT),@"food_alias_id":@"1"};
            [SN_FoodClass.foodArray addObject:dicT];
        }
    }
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if (range.length == 1 && string.length == 0) {
        return YES;
    }
    
      if (textField.tag == 100 || textField.tag == 101) {
          if (textField.text.length >5) {
//            SHOWMBProgressHUD(SN_Text(@"太长了,请切换单位"), nil, nil, NO, 0.5);
            return NO;
          }
          NSMutableString * futureString = [NSMutableString stringWithString:textField.text];
          [futureString  insertString:string atIndex:range.location];
          NSInteger flag=0;
          const NSInteger limited = 1;//小数点后需要限制的个数
          for (int i = futureString.length-1; i>=0; i--) {
              
              if ([futureString characterAtIndex:i] == '.') {
                  if (flag > limited) {
                      return NO;
                  }
                  break;
              }
              flag++;
          }
          return YES;
      }
    
     if (textField.tag == 200 || textField.tag == 201) {
         if (textField.text.length >5) {
//           SHOWMBProgressHUD(SN_Text(@"太长了,请切换单位"), nil, nil, NO, 0.5);
             return NO;
         }
     }
    return YES;
}

- (void)weightTxChange:(UITextField *)textField {
    if (textField.tag == 100 || textField.tag == 101) {
        NSUInteger row = textField.tag - 100;
        [self updateCurrentCellWith:row];
    }
}

- (void)calorTxChange:(UITextField *)textField {
    if (textField.tag == 200 || textField.tag == 201) {
        NSUInteger row = textField.tag - 200;
        NSDictionary *dict = [_snFoodArray objectAtIndex:row];
        NSDictionary *dic = @{@"name":dict[@"name"],@"calory":textField.text,@"unit":dict[@"unit"],@"amount":dict[@"amount"]};
        [_snFoodArray replaceObjectAtIndex:row withObject:dic];
    }
}

- (void)textFieldDidEndEditing:(UITextField *)textField {
    if (textField.tag == 100 || textField.tag == 101) {
        if (textField.text.length > 6) {
            SHOWMBProgressHUD(SN_Text(@"太长了,请切换单位"), nil, nil, NO, 0.5);
            return;
        }
        NSUInteger row = textField.tag %10;
        [self updateCurrentCellWith:row];
    }
}

- (BOOL)isFullFoodDic:(NSDictionary *)dic {
    BOOL     ok        = YES;
    NSString *foodName = dic[@"name"];
    NSString *amount   = dic[@"amount"];
    NSString *unit     = dic[@"unit"];
    NSString *calory   = dic[@"calory"];
    
    if (foodName.length == 0 || [foodName isEqualToString:SN_Text(@"请输入关键字")]) {
        ok = NO;
    }
    if (amount.integerValue == 0) {
        ok = NO;
    }
    if (unit.length == 0) {
        ok = NO;
    }
    if (calory.length == 0) {
        ok = NO;
    }
    
    return ok;
}

- (BOOL)checkEmpty
{
    BOOL empty = YES;
    for (int j = 0; j <_dataArray.count; j++) {
        NSIndexPath                 *indexPath   = [NSIndexPath indexPathForRow:j inSection:0];
        SNFoodMealEditTableViewCell *cell        = [self.tableView cellForRowAtIndexPath:indexPath];
        NSString                    *getFoodName = cell.jjSearchView.foodNames;
        NSString *amout = cell.weightTx.text;
        NSString *unit = cell.unitJJSearchView.title;
        NSString *calor = cell.calorTx.text;
        if ([getFoodName isEqualToString:SN_Text(@"请输入关键字")]&&amout.length==0 &&unit.length ==0 &&calor.length == 0) {
            empty = NO;
        }else if(getFoodName.length ==0&&amout.length==0 &&unit.length ==0 &&calor.length == 0)
        {
           empty = NO;
        }
        else if (![getFoodName isEqualToString:SN_Text(@"请输入关键字")]&&getFoodName.length>0 &&amout.length >0&&unit.length >0 &&calor.length >0) {
            empty = NO;
        }
        else
        {
            empty = YES;
        }
    }
    return empty;
}

- (void)endAndSave {

    NSLog(@"当前用餐>>>>>>>%@", _snFoodArray);
    NSMutableArray *array     = [NSMutableArray array];
    float          calorTotal = 0.0;
    BOOL           save       = YES;
    for (NSDictionary *dic in _snFoodArray) {
        BOOL ok = [self isFullFoodDic:dic];
        if (ok) {
            [array addObject:dic];
            NSString *calory = dic[@"calory"];
            calorTotal += calory.floatValue;
        }
    }
    
    _model.caloryTotal = calorTotal;
    
    if (_model.caloryTotal == 0) {
        save = NO;
    }
    
    BOOL empty =  [self checkEmpty];
    if (empty) {
        save = NO;
    }
   
    if (save) {
    } else {
        SHOWMBProgressHUD(SN_Text(@"请输入完整信息"), nil, nil, NO, 1.0);
        return;
    }
    
    SN_FoodClass.foodListArray = [NSMutableArray arrayWithArray:array];
    NSLog(@"当前用餐(save)>>>>>>%@",SN_FoodClass.foodListArray);
    
     [SN_Net showHUD:SN_Text(@"请等待...") withTime:10.0];
    if (self.add) {
        [SN_Net FoodAddWithFoodModel:_model Success:^(id object) {
            SHOWMBProgressHUD(SN_Text(@"添加成功"), nil, nil, NO, 1.0);
            [self functionSetLeft];
        } fail:^(id object) {
        }];
    } else {
        [SN_Net FoodEditWithFoodModel:_model Success:^(id object) {
            SHOWMBProgressHUD(SN_Text(@"编辑成功"), nil, nil, NO, 1.0);
            [self functionSetLeft];
        } fail:^(id object) {

        }];
    }
}

// 当输入食物/体重/单位变化的时候 去重新计算calor
// 当前tag只有0 / 1   服务器的卡路里以每100g去换算
- (void)updateCurrentCellWith:(NSInteger)tag {
    NSIndexPath                 *indexPath   = [NSIndexPath indexPathForRow:tag inSection:0];
    SNFoodMealEditTableViewCell *cell        = [self.tableView cellForRowAtIndexPath:indexPath];
    NSString                    *getFoodName = cell.jjSearchView.foodNames;
    
    if (getFoodName.length == 0 || [getFoodName isEqualToString:SN_Text(@"请输入关键字")]) {
        SHOWMBProgressHUD(SN_Text(@"请输入食材"), nil, nil, NO, 0.5);
    }
    if (cell.weightTx.text.intValue == 0) {
        SHOWMBProgressHUD(SN_Text(@"请输入份量"), nil, nil, NO, 0.5);
    }
    if (cell.unitJJSearchView.title.length == 0) {
        SHOWMBProgressHUD(SN_Text(@"请输入单位"), nil, nil, NO,0.5);
    }
    NSDictionary *dic          = [SN_FoodClass getFoodWithName:getFoodName];
    NSString     *calorUnit    = dic[@"calory"];
    CGFloat      currentWeight = cell.weightTx.text.floatValue;
    CGFloat      weight        = 1.0*currentWeight /100 *calorUnit.floatValue;
    NSString     *unitString   = cell.unitJJSearchView.title;
    CGFloat      calor         = weight *[SN_FoodClass getMultipleWithUnit:unitString];
    CGFloat calorS = roundf(calor);
    if (self.isSelectFood) {
        cell.calorTx.text = [NSString stringWithFormat:@"%d",(int)calorS];
    } else {
        NSLog(@"自己添加的食物卡路里");
    }
    NSString *unit = cell.unitJJSearchView.title;
    NSDictionary *dict = @{@"name":getFoodName, @"unit":unit, @"calory":cell.calorTx.text, @"amount":cell.weightTx.text};
    [_snFoodArray replaceObjectAtIndex:tag withObject:dict];
    
}

- (void)searchOptionView:(JJSearchOptionView *)optionView selctedString:(NSString *)selctedString
{
    NSDictionary *dic = [_snFoodArray objectAtIndex:optionView.tag];
    [dic setValue:selctedString forKey:@"name"];
    [_snFoodArray replaceObjectAtIndex:optionView.tag withObject:dic];
    self.isSelectFood = NO;
}

// 食物搜索选择回调
- (void)searchOptionView:(JJSearchOptionView *)optionView selctedString:(NSString *)selctedString selectedIndex:(NSInteger)selectedIndex {
    NSLog(@"OptionView Tag >>>%d selctedString:%@ selectedIndex>>>%d", optionView.tag, selctedString, selectedIndex);
    for (UIView *view in optionView.subviews) {
        if ([view isKindOfClass:[UITextField class]]) {
            UITextField *textFiled = (UITextField *)view;
            [textFiled resignFirstResponder];
        }
    }
    self.isSelectFood = YES;
    [self updateCurrentCellWith:optionView.tag];
}

// 单位选择回调
- (void)optionView:(JJOptionView *)optionView selectedIndex:(NSInteger)selectedIndex selectString:(NSString *)string {
    NSLog(@"OptionView Tag >>>%d selctedString:%@ selectedIndex>>>%d", optionView.tag, string, selectedIndex);
    [self updateCurrentCellWith:optionView.tag];
}

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
    [textField resignFirstResponder];
    return YES;
}

- (void)functionSetLeft {
    [self.navigationController popViewControllerAnimated:YES];
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
